﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Configuration;

namespace IndustrialMusicWindowsCSharp {
    public partial class ScreenScrapeS107 : Form {
        public ScreenScrapeS107() {
            InitializeComponent();
        }

        //  Use threading to update UI.
        private void ProcessContents(byte[] pageContents, string alphabetCode) {
            UTF8Encoding encoder = new UTF8Encoding();
            string contents = encoder.GetString(pageContents);

            if (contents.Length != 0) {
                StreamWriter writer = new StreamWriter(ConfigurationManager.AppSettings["ScreenScrapeDestination107"] + alphabetCode + ".txt");
                writer.Write(contents);
                writer.Close();
                writer.Dispose();
            }
        }

        private void btnScreenScrape_Click(object sender, EventArgs e) {
            WebClient browser = new WebClient();

            for (Int64 i = 0; i <= 25; i++) {
                string alphabetCode = Utilities.Base26Encode(i);

                Uri websiteAddress = new Uri(@"http://s107.net/index.php?index=" + alphabetCode.ToUpper());
                websiteLabel.Text = websiteAddress.ToString();

                try {
                    byte[] pageContents = browser.DownloadData(websiteAddress);
                    ProcessContents(pageContents, alphabetCode);
                } catch {
                    txtMessages.Text += "No artists for alphabetCode: " + alphabetCode + Environment.NewLine;
                }
            }

            MessageBox.Show("Completed screen scraping!");
        }
    }
}
